this
The keyword this
belongs to functions, (or when used alone, the global object
).
this
is effectively a pointer to that function
/object
.
Here is an example:
There are different contexts of using this
:
Global context: when
this
is called outside of a function, it refers to the global object. (window in a browser for example)Function context: calling
this
in a function refers to the object the function belongs to.- If said function is alone, this refers globally.
Class context: refers to the properties/members of that class in an instance of it
info
We can change what this
refers to, especially in function contexts, using binding
methods (shown soon).
Here's another example of this
used in an object
setting:
Binding this
We can change what this
refers to by using certain methods:
bind()
can set a function'sthis
value. Note that arrow functions don't have their ownthis
bindingcall()
will bind a function'sthis
to the first parameter put incall()
apply()
similar tocall()
Let's see an example:
Regarding the bind()
method, a function calls bind()
with an object
parameter.
This leads to a creation of a new, equal function.
this
will then be bound permanently in the new function to said parameter.
Let's see another example to clarify:
tip
For more detailed information regarding this
, visit: this - MDN